package com.blast.cn.ui

import android.text.TextUtils
import android.view.KeyEvent
import android.widget.EditText
import com.blast.cn.R
import com.lxj.xpopup.XPopup
import com.wxl.common.AppContext
import com.wxl.common.base.AbsActivity
import com.wxl.common.serialport.CmdCode
import com.wxl.common.serialport.Serial
import com.wxl.common.serialport.SerialPortManager
import com.wxl.common.serialport.Serials
import com.wxl.common.util.KeyBoardUtil
import com.wxl.common.util.Toll
import kotlinx.android.synthetic.main.activity_voltage_settings.*

class VoltageSettingsActivity : AbsActivity() {

    var autoUnderData = ""


    override fun getCreateContentViewId(): Int {
        return R.layout.activity_voltage_settings
    }

    override fun onCreateViewChanged() {
        SerialPortManager.openOnlyPort(object : SerialPortManager.Companion.OpenPortCallback{
            override fun onOpenPort(state: Int) {
                if(state != 0){
                    Toll.toll("打开串口失败")
                    finish()
                }
            }
        })
        setTopTitle("设置电压")
        voltageSettingAutoDown.isChecked = AppContext.appContext.isAutoUnderPlan()
        voltageSettingSubmit.setOnClickListener {
            AppContext.appContext.saveAutoUnderPlan(voltageSettingAutoDown.isChecked)
            submit()
        }
        showAutoUnderPlan()
    }

    override fun onKeyDownEvent(keyCode: Int, event: KeyEvent?): Boolean {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            finish()
        }
        if(keyCode == KeyEvent.KEYCODE_ENTER){
            voltageSettingSubmit.performClick()
        }
        return true
    }

    /**
     * 显示上次设置的下传方案
     */
    private fun showAutoUnderPlan() {
        val data = AppContext.appContext.getAutoUnderData()
        if (!TextUtils.isEmpty(data)) {
            voltageSettingTongXun.setText(Integer.valueOf(data.substring(12, 14), 16).toString())
            voltageSettingCharge.setText(Integer.valueOf(data.substring(14, 16), 16).toString())
            voltageSettingQuery.setText(Integer.valueOf(data.substring(16, 18), 16).toString())
            voltageSettingChargeAdc.setText(Integer.valueOf(data.substring(18, 20), 16).toString())
            voltageSettingBlastAdc.setText(Integer.valueOf(data.substring(20, 22), 16).toString())
            voltageSettingReserved1.setText(Integer.valueOf(data.substring(22, 24), 16).toString())
            voltageSettingReserved2.setText(Integer.valueOf(data.substring(24, 26), 16).toString())
            voltageSettingReserved3.setText(Integer.valueOf(data.substring(26, 28), 16).toString())
            voltageSettingReserved4.setText(Integer.valueOf(data.substring(28, 30), 16).toString())
        }
    }

    /**
     * 提交设置电压
     */
    private fun submit(){
        hideKeyBorad()

        val dialog = XPopup.Builder(this)
            .dismissOnBackPressed(false)
            .dismissOnTouchOutside(false)
            .asLoading("正在设置...")

        addPop(dialog.show())

        autoUnderData = ping(voltageSettingTongXun,voltageSettingCharge,voltageSettingQuery,voltageSettingChargeAdc,
            voltageSettingBlastAdc,voltageSettingReserved1,voltageSettingReserved2,voltageSettingReserved3,
            voltageSettingReserved4)
        Serials.registerSingleStartHexSerial(CmdCode.SETTING_VOLTAGE_OK_ASK,object : Serial(){
            override fun loadReceiveData(data: String) {
                dismissClearAllPop()
                AppContext.appContext.saveAutoUnderData(autoUnderData)
                Toll.toll("设置成功")
                finish()
            }
        })
        Serials.registerSingleStartHexSerial(CmdCode.SETTING_VOLTAGE_E_ASK,object : Serial(){
            override fun loadReceiveData(data: String) {
                dismissClearAllPop()
                Toll.toll("设置失败")
            }
        })
        SerialPortManager.send(CmdCode.SETTING_VOLTAGE_CMD+autoUnderData)
    }


    /**
     * 获得输入的数据
     */
    private fun ping(vararg ets: EditText):String{
        val data = StringBuffer()
        ets.forEach {
            var text = "0"
            if(!TextUtils.isEmpty(it.text)){
                text = it.text.toString()
            }
           val hex = Integer.toHexString(text.toInt())
            if(hex.length == 1){
                data.append("0")
            }
            data.append(hex)
        }
        return data.toString()
    }


    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        hideKeyBorad()
    }

    private fun hideKeyBorad(){
        KeyBoardUtil.hideSoftInput(voltageSettingTongXun)
        KeyBoardUtil.hideSoftInput(voltageSettingCharge)
        KeyBoardUtil.hideSoftInput(voltageSettingQuery)
        KeyBoardUtil.hideSoftInput(voltageSettingChargeAdc)
        KeyBoardUtil.hideSoftInput(voltageSettingBlastAdc)
        KeyBoardUtil.hideSoftInput(voltageSettingReserved1)
        KeyBoardUtil.hideSoftInput(voltageSettingReserved2)
        KeyBoardUtil.hideSoftInput(voltageSettingReserved3)
        KeyBoardUtil.hideSoftInput(voltageSettingReserved4)
    }

}